#include "register.h"
#include "random.h"
#include <stdlib.h>
#include <stdio.h>

/*
 * Register *new_register(void);
 * Constructs a new register and returns a pointer to it.
 */
Register *new_register(void)
{
	return (Register *)malloc(sizeof(Register));
}

/*
 * void register_initialize(Register *reg);
 * Initializes a new register to an arbitrary, random value.
 * reg: a pointer to the register to initialize
 */
void register_initialize(Register *reg)
{
	int i;
	for (i = 0; i < REGISTER_BITS; i++)
		register_set_bit(reg, i, random_number(2));
}

/*
 * void register_set(Register *reg, unsigned short value);
 * Sets the register to the specified value.
 * reg: a pointer to the register to modify
 * value: the 16-bit value to put in the register
 */
void register_set(Register *reg, unsigned short value)
{
	*reg = value;
}

/*
 * unsigned short register_get(Register *reg);
 * Gets the value of the register.
 * reg: a pointer to the register to get the value of
 */
unsigned short register_get(Register *reg)
{
	return *reg;
}

/*
 * int register_get_bit(Register *reg, int bit_index);
 * Gets the value of a bit in the register.
 * reg: a pointer to the register to get a bit value from
 * bit_index: the 0-based index of the bit to get
 */
Bit register_get_bit(Register *reg, int bit_index)
{
	unsigned short bit_mask = 1 << bit_index;
	unsigned short value = *reg & bit_mask;
	
	if (value)
		return TRUE;
	else
		return FALSE;
}

/*
 * void register_set_bit(Register *reg, int bit_index, Bit bit_value);
 * Sets the value of a bit in the register.
 * reg: a pointer to the register to modify
 * bit_index: the 0-based index of the bit to set
 * bit_value: 0 to clear the bit, non-zero to set the bit
 */
void register_set_bit(Register *reg, int bit_index, Bit bit_value)
{
	unsigned short bit_mask = 1 << bit_index;
	
	if (bit_value)
		*reg |= bit_mask;
	else
		*reg &= ~bit_mask;
}

/*
 * void delete_register(Register *reg);
 * Frees the memory associated with the register.
 * reg: a pointer to the register to delete
 */
void delete_register(Register *reg)
{
	free(reg);
}
